package com.luculent.inter;

import java.util.List;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {

    /**
     * controller 执行之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	String url = request.getRequestURI(); 
    	if(passUrl(url)){
    		return true;
    	}
    	//检验 请求中是否包含iw-apikey
    	String iwApikey = getApiKey(request); 
    	if(StringUtils.isBlank(iwApikey)){
    		response.sendRedirect (request.getContextPath()+"/error/msg?iw-apikey=123"); 
    		return false; 
    	}
    	//将请求中包含iw-cmd参数的进行转发到path=iw-cmd的requestmapping上
    	String query = request.getQueryString();
    	if(query.indexOf("iw-cmd=") >=0){
			List<String> queryList = Lists.newArrayList(Splitter.on("&").omitEmptyStrings().trimResults().split(query));
			String cmd = "";
			for(String queryKv : queryList){
				if(queryKv.indexOf("iw-cmd=") >=0 ){
					cmd = queryKv;
					queryList.remove(queryKv);
					break;
				}
			}
			String queryStr = Joiner.on("&").skipNulls().join(queryList);
			String path = request.getContextPath() + url + "/" + cmd.split("=")[1] + "?" + queryStr;
			response.setHeader("iw-apikey",iwApikey);
			response.sendRedirect(path); 
			log.debug(path);
			return false; 
		}else{
    		return true;
    	}
    }
    
    private String getApiKey(HttpServletRequest request){
    	//检验 iw-apikey的 
    	String iwApikey = request.getHeader("iw-apikey");
    	return StringUtil.isBlank(iwApikey) ? request.getParameter("iw-apikey") : iwApikey;
    	
    }
    
    private boolean passUrl(String url){
    	PathMatcher matcher = new AntPathMatcher();
    	if(Stream.of("/doc.html**","/swagger-ui.html**",
    			"/swagger-resources/**",
    			"/webjars/**", "/v2/**",
    			"/css/**","/js/**",
    			"/fonts/**","/img/**","/docs/**").anyMatch(u -> matcher.match(u,url))){
    		return true;
    	}
    	return false;
    }
    
    

//    /**
//     * controller 执行之后，且页面渲染之前调用
//     */
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
//            ModelAndView modelAndView) throws Exception {
//        log.debug("------postHandle-----");
//    }
//
//    /**
//     * 页面渲染之后调用，一般用于资源清理操作
//     */
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
//            throws Exception {
//        log.debug("------afterCompletion-----");
//
//    }

}